package com.bfl.sa.sys.user.service;

import com.bfl.sa.common.mybatis.entity.Query;
import com.bfl.sa.common.service.BaseService;
import com.bfl.sa.sys.user.entity.UserOnline;
import com.bfl.sa.sys.user.mapper.UserOnlineMapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class UserOnlineService extends BaseService<UserOnline, String> {

    @Resource
    private UserOnlineMapper userOnlineMapper;

    /**
     * 上线
     */
    public void online(UserOnline userOnline) {
        super.save(userOnline);
    }

    /**
     * 下线
     */
    public void offline(String sid) {
        UserOnline userOnline = super.findOne(sid);
        if (userOnline != null) {
            delete(userOnline);
        }
        //游客 无需记录上次访问记录
        //此处使用数据库的触发器完成同步
//        if(userOnline.getUserId() == null) {
//            userLastOnlineService.lastOnline(UserLastOnline.fromUserOnline(userOnline));
//        }
    }

    /**
     * 批量下线
     */
    public void batchOffline(List<String> needOfflineIdList) {
        userOnlineMapper.batchDelete(needOfflineIdList);
    }

    /**
     * 无效的UserOnline
     */
    public Page<UserOnline> findExpiredUserOnlineList(Date expiredDate, Pageable pageable) {
        Query query = Query.newQuery(pageable);
        query.put("expiredDate", expiredDate);

        return PageHelper.startPage(query).doSelectPage(() -> userOnlineMapper.findExpiredUserOnlineList(query));
    }


}
